<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="900px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-col :span="24">
              <el-form-item
                label="真实姓名"
                prop="userInfoAo.userName"
                :rules="rules.userName"
              >
                <el-input
                  class="data-input"
                  v-model="form.userInfoAo.userName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="手机号码"
                prop="userInfoAo.userPhone"
                :rules="rules.userPhone"
              >
                <el-input
                  class="data-input"
                  v-model="form.userInfoAo.userPhone"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  class="data-input"
                  v-model="form.coreUserMetaInfo.idCard"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="所属单位"
                prop="coreUserMetaInfo.unitContent"
                :rules="rules.unitContent"
                v-if="form.userInfoAo.type === '2'"
              >
                <el-select
                  class="search-select"
                  v-model="form.coreUserMetaInfo.unitContent"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of tenantOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.pkid"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="所属单位"
                prop="coreUserMetaInfo.unitContent"
                :rules="rules.unitContent"
                v-else-if="form.userInfoAo.type === '3'"
              >
                <el-select
                  class="search-select"
                  v-model="form.coreUserMetaInfo.unitContent"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of relatedOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.pkid"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="所属单位"
                prop="coreUserMetaInfo.unitContent"
                :rules="rules.unitContent"
                v-else
              >
                <el-input
                  class="data-input"
                  v-model="form.coreUserMetaInfo.unitContent"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.userInfoAo.type === '2'">
              <el-form-item
                label="主岗"
                prop="coreUserMetaInfo.mainPost"
                :rules="rules.mainPost"
              >
                <el-select
                  class="search-select"
                  v-model="form.coreUserMetaInfo.mainPost"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of dict['main_post']"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车牌号码" prop="cardNo">
                <el-input
                  class="data-input"
                  v-model="form.coreUserMetaInfo.cardNo"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="访问有效期"
                prop="coreUserMetaInfo.time"
                :rules="rules.time"
              >
                <el-date-picker
                  v-model="form.coreUserMetaInfo.time"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <!--              <el-form-item-->
              <!--                label="访问区域"-->
              <!--                prop="coreUserMetaInfo.visitRegionId"-->
              <!--                :rules="rules.visitRegionId"-->
              <!--              >-->
              <!--                <el-select-->
              <!--                  class="search-select"-->
              <!--                  v-model="form.coreUserMetaInfo.visitRegionId"-->
              <!--                  placeholder="请选择"-->
              <!--                  multiple-->
              <!--                >-->
              <!--                  <el-option-->
              <!--                    v-for="(item, index) of keyAreaOptions"-->
              <!--                    :key="index"-->
              <!--                    :label="item.name"-->
              <!--                    :value="item.pkid"-->
              <!--                  />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  class="data-input"
                  v-model="form.userInfoAo.remark"
                  placeholder="请输入"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-col :span="24" v-if="!form.userInfoAo.pkid">
              <el-form-item
                label="密码"
                prop="userInfoAo.loginPassword"
                :rules="rules.loginPassword"
              >
                <el-input
                  class="data-input"
                  v-model="form.userInfoAo.loginPassword"
                  placeholder="请输入"
                  show-password
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="!form.userInfoAo.pkid">
              <el-form-item
                label="确认密码"
                prop="userInfoAo.reLoginPassword"
                :rules="rules.reLoginPassword"
              >
                <el-input
                  class="data-input"
                  v-model="form.userInfoAo.reLoginPassword"
                  placeholder="请输入"
                  show-password
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="角色" prop="roleId">
                <el-select
                  class="search-select"
                  v-model="form.userInfoAo.roleId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of roleOptions"
                    :key="index"
                    :label="item.roleName"
                    :value="item.pkid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否启用" prop="userState">
                <el-radio-group v-model="form.userInfoAo.userState">
                  <el-radio
                    v-for="(item, index) of dict['yn']"
                    :key="index"
                    :value="Number(item.value)"
                    >{{ item.name }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="人员照片">
                <VUpload
                  :limit="1"
                  listType="picture-card"
                  uploadText=""
                  accept=".png, .jpg, .jepg"
                  v-model="form.coreUserMetaInfo.files"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.userInfoAo.type === '3'">
              <el-form-item label="身份证照片(正)">
                <VUpload
                  :limit="1"
                  listType="picture-card"
                  uploadText=""
                  accept=".png, .jpg, .jepg"
                  v-model="form.coreUserMetaInfo.cardFilesFront"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.userInfoAo.type === '3'">
              <el-form-item label="身份证照片(反)">
                <VUpload
                  :limit="1"
                  listType="picture-card"
                  uploadText=""
                  accept=".png, .jpg, .jepg"
                  v-model="form.coreUserMetaInfo.cardFilesReverse"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { cardId } from '@/utils/validate'
import { useDict } from '@/hooks/useDict'
import VUpload from '@/components/upload/index.vue'
import { getUserDetail, userAdd } from '@/api/manager/systemManage/user.js'
import { getKeyAreaList } from '@/api/manager/dataManage/keyAreaManage.js'
import { getRoleList } from '@/api/manager/systemManage/role.js'
import { tenantPageList } from '@/api/manager/dataManage/tenant.js'
import { relatedPageList } from '@/api/manager/dataManage/related'

const { dict } = useDict(['yn', 'main_post'])
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    } else {
      form.value.userInfoAo.type = props.detail.type
    }
  },
)
const handleDetail = async () => {
  const res = await getUserDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理有效期
    res.data.coreUserMetaInfo.time = [
      res.data.coreUserMetaInfo.visitStartTime,
      res.data.coreUserMetaInfo.visitEndTime,
    ]
    // 处理人员照片
    if (res.data.coreUserMetaInfo.faceId) {
      res.data.coreUserMetaInfo.files = [
        {
          pkid: res.data.coreUserMetaInfo.faceId,
          fileUrl: res.data.coreUserMetaInfo.faceUrl,
        },
      ]
    } else {
      res.data.coreUserMetaInfo.files = []
    }
    // 处理人员身份证照片
    if (res.data.coreUserMetaInfo.idCardFront) {
      res.data.coreUserMetaInfo.cardFilesFront = [
        {
          pkid: res.data.coreUserMetaInfo.idCardFront,
          fileUrl: res.data.coreUserMetaInfo.frontUrl,
        },
      ]
    } else {
      res.data.coreUserMetaInfo.cardFilesFront = []
    }
    if (res.data.coreUserMetaInfo.idCardReverse) {
      res.data.coreUserMetaInfo.cardFilesReverse = [
        {
          pkid: res.data.coreUserMetaInfo.idCardReverse,
          fileUrl: res.data.coreUserMetaInfo.reverseUrl,
        },
      ]
    } else {
      res.data.coreUserMetaInfo.cardFilesReverse = []
    }

    // 处理访问区域
    // res.data.coreUserMetaInfo.visitRegionId = res.data.coreUserMetaInfo
    //   .visitRegionId
    //   ? res.data.coreUserMetaInfo.visitRegionId.split(',')
    //   : []

    form.value = {
      userInfoAo: res.data.userInfo,
      coreUserMetaInfo: res.data.coreUserMetaInfo,
    }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = {
    userInfoAo: {
      userState: 1,
      isPatrol: 0,
      type: '',
    },
    coreUserMetaInfo: {
      time: [],
      files: [],
      cardFilesFront: [],
      cardFilesReverse: [],
      isPatrol: 0,
      visitRegionId: '',
    },
  }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
const treeData = ref([])
const keyAreaOptions = ref([])
const initKeyAreaOptions = async () => {
  const res = await getKeyAreaList({
    pageIndex: 1,
    pageSize: 9999,
  })
  keyAreaOptions.value = res.data.list
}
const roleOptions = ref([])
const initRoleOptions = async () => {
  const res = await getRoleList({ pageIndex: 1, pageSize: 9999 })
  roleOptions.value = res.data.list
}
const tenantOptions = ref([])
const initTenantOptions = async () => {
  const res = await tenantPageList({ pageIndex: 1, pageSize: 9999 })
  tenantOptions.value = res.data.list
}
const relatedOptions = ref([])
const initRelatedOptions = async () => {
  const res = await relatedPageList({ pageIndex: 1, pageSize: 9999 })
  relatedOptions.value = res.data.list
}
watch(
  () => dialogVisible.value,
  async () => {
    if (dialogVisible.value) {
      initTreeData()
      initKeyAreaOptions()
      initRoleOptions()
      initTenantOptions()
      initRelatedOptions()
    }
  },
)
const initTreeData = async () => {}
const formRef = ref(null)
const form = ref({
  userInfoAo: {
    userState: 1,
    isPatrol: 0,
  },
  coreUserMetaInfo: {
    time: [],
    files: [],
    cardFilesFront: [],
    cardFilesReverse: [],
    isPatrol: 0,
    visitRegionId: '',
  },
})
const validateIdCard = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const list = cardId(value)
    if (value && list[0]) {
      callback(new Error(list[1]))
    } else {
      callback()
    }
  }
}
const rules = ref({
  userName: [{ required: true, message: '请输入人员名称', trigger: 'blur' }],
  userPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[34578]\d{9}$/,
      message: '请输入正确手机号',
      trigger: 'blur',
    },
  ],
  loginPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
      message: '至少包含大写字母、小写字母、数字和特殊符号中其中三种',
      trigger: 'blur',
    },
  ],
  reLoginPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
      message: '至少包含大写字母、小写字母、数字和特殊符号中其中三种',
      trigger: 'blur',
    },
  ],
  idCard: [
    {
      validator: validateIdCard,
    },
  ],
  unitContent: [{ required: true, message: '请输入所属单位', trigger: 'blur' }],
  mainPost: [{ required: true, message: '请输入主岗', trigger: 'blur' }],
  relationUnitId: [
    { required: true, message: '请输入所属单位', trigger: 'blur' },
  ],
  time: [{ required: true, message: '请选择访问有效期', trigger: 'blur' }],
  visitRegionId: [
    { required: true, message: '请选择访问区域', trigger: 'blur' },
  ],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))

      // 处理人员图片
      if (
        params.coreUserMetaInfo.files &&
        params.coreUserMetaInfo.files.length > 0
      ) {
        params.coreUserMetaInfo.faceId = params.coreUserMetaInfo.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.coreUserMetaInfo.faceId = ''
      }
      delete params.coreUserMetaInfo.files
      // 处理身份证图片
      if (
        params.coreUserMetaInfo.cardFilesFront &&
        params.coreUserMetaInfo.cardFilesFront.length > 0
      ) {
        params.coreUserMetaInfo.idCardFront =
          params.coreUserMetaInfo.cardFilesFront
            .map((i) => {
              return i.pkid
            })
            .join(',')
      } else {
        params.coreUserMetaInfo.idCardFront = ''
      }
      if (
        params.coreUserMetaInfo.cardFilesReverse &&
        params.coreUserMetaInfo.cardFilesReverse.length > 0
      ) {
        params.coreUserMetaInfo.idCardReverse =
          params.coreUserMetaInfo.cardFilesReverse
            .map((i) => {
              return i.pkid
            })
            .join(',')
      } else {
        params.coreUserMetaInfo.idCardReverse = ''
      }
      delete params.coreUserMetaInfo.cardFilesReverse
      // 处理有效期
      if (
        params.coreUserMetaInfo.time &&
        params.coreUserMetaInfo.time.length > 0
      ) {
        params.coreUserMetaInfo.visitStartTime = params.coreUserMetaInfo.time[0]
        params.coreUserMetaInfo.visitEndTime = params.coreUserMetaInfo.time[1]
      }
      delete params.coreUserMetaInfo.time
      // 处理访问区域
      // params.coreUserMetaInfo.visitRegionId =
      //   params.coreUserMetaInfo.visitRegionId.length > 0
      //     ? params.coreUserMetaInfo.visitRegionId.join(',')
      //     : ''
      // 处理密码、账号
      if (!params.userInfoAo.pkid) {
        params.userInfoAo.loginPassword = window.btoa(
          params.userInfoAo.loginPassword,
        )
        params.userInfoAo.loginName = params.userInfoAo.userPhone
      }
      delete params.userInfoAo.reLoginPassword

      try {
        let res = await userAdd(params)
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
defineExpose({ dialogVisible, title })
onMounted(() => {})
</script>
<style lang="scss" scoped></style>
